package com.nextgenapp.fbgraph.basic
{
	import com.adobe.serialization.json.JSON;
	import com.nextgenapp.fbgraph.util.FbUrlUtil;
	
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	/**
	 * get data using graph api.  
	 * 
	 * eg. do a http get on http://graph.facebook.com/me/friends to get friends data.  
	 * 
	 * @example 
	 * 
	 * <listing version="3.0">
	 * 
	 * </listing>
	 * 
	 */
	public class GetData
	{
		/** api url.  url to retrieve the data.  
		 * usually in the form of 
		 * http://graph.facebook.com/{id}/{connections} 
		 * 
		 * eg. http://graph.facebook.com/me/friends
		 * http://graph.facebook.com/123123432
		 */
		public var apiUrl:String = null;
		
		public var access_token:String = null;
		
		private var callback:Function = null;
		
		private var service:HTTPService = null;
				
		public function GetData(callback:Function=null)
		{
			this.callback = callback;
		}
		
		public function getData():void {
			service = new HTTPService();			
            service.url = FbUrlUtil.appendAccessToken(apiUrl, access_token);            
            service.method = "GET";
            service.resultFormat = "text";
            service.addEventListener("result", httpResult);
            service.addEventListener("fault", httpFault);
            if (apiUrl && access_token) {
	            service.send();
	        } else {
	        	trace("Error: apiUrl or access_token not provided.  apiUrl="+apiUrl+".  access_token="+access_token);
	        }
		}
		
	    public function httpResult(event:ResultEvent):void {
	        var sResult:String = event.result as String;
	        trace("result from "+ service.url + "= \n" + sResult);
	        if (sResult) {
	        	var result:Object = JSON.decode(sResult);
	        	// once results is in, do callback
		        if (callback != null) {
		        	var callbackResult:FbCallbackResult = new FbCallbackResult();
		        	callbackResult.success = true;
		        	callbackResult.result = result;
		        	callback(callbackResult);
		        }
	        } 
        }

        public function httpFault(event:FaultEvent):void {
        	var faultstring:String = event.fault.faultString;
        	trace("GetData.httpFault(): " + faultstring + ".  accessing url="+service.url);
        	if (callback != null) {
        		// callback with the error.  
        		var callbackResult:FbCallbackResult = new FbCallbackResult();
        		callbackResult.success = false;
        		callbackResult.faultEvent = event;
        		callbackResult.url = service.url;
        		
        		callback(callbackResult);
        	}
            
            
        }
		
		

	}
}